package com.carrot.ai.controller;

import com.carrot.ai.enums.ServiceType;
import com.carrot.ai.repository.ChatHistoryRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.content.Media;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/ai")
public class ChatController {

    @Autowired
    private ChatClient qwenChatClient;

    @Autowired
    private ChatHistoryRepository chatHistoryRepository;

    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
    public Flux<String> chat(@RequestParam(defaultValue = "讲个笑话") String prompt, @RequestParam String chatId, @RequestParam List<MultipartFile> files) {
        // 保存会话id
        chatHistoryRepository.save(ServiceType.CHAT, chatId);

        if(files != null && !files.isEmpty()) {
            return multiModelChat(files, prompt, chatId);
        } else {
            return textChat(prompt, chatId);
        }
    }

    private Flux<String> multiModelChat(List<MultipartFile> files, String prompt, String chatId) {
        List<Media> mediaList = files.stream().
                map(file -> new Media(
                        MediaType.valueOf(Objects.requireNonNull(file.getContentType())),
                        file.getResource()
                ))
                .toList();

        return qwenChatClient
                .prompt() // 传入user提示词
                .user(p -> p.media(mediaList.toArray(Media[]::new)).text(prompt))
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();//返回响应内容
    }

    private Flux<String> textChat(String prompt, String chatId) {
        return qwenChatClient
                .prompt(prompt) // 传入user提示词
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();//返回响应内容
    }

}
